from django.http import HttpResponse
from django.shortcuts import render
# from .models import Category,Article,Tag
# Create your views here.

# def index(request):
#     # article = Article(title='abc',content='111')
#     # category = Category(name='最新文章')
#     # category.save()     # 先保存
#     # article.category = category # 会判断category是否存在，不存在就报错，所以要先保存
#     # article.save()
#     article = Article.objects.first()
#     print(article.category.name)
#     return HttpResponse('succese')
#
# def delete_view(request):
#     cateory = Category.objects.get(pk=1)
#     cateory.delete()
#     return HttpResponse("delete success")
#
# def one_to_many_view(request):
#     # # 一对多的关联操作
#     # article = Article(title="钢铁是怎样练成的",content='abc')
#     # category = Category.objects.first()
#     # author = FrontUser.objects.first()
#     #
#     # article.category = category
#     # article.author = author
#     #
#     # article.save()
#
#     # 2.获取某个分类下所有的文章
#     category = Category.objects.first()
#     article = category.article_set.all()
#     for article in article:
#         print(article)
#     return HttpResponse('success')
#
# def many_to_many_views(request):
#     article = Article.objects.first()
#     tag = Tag(name="热门文章")
#     article.save()
#     article.tag_set.add(tag)
#     return HttpResponse('succese')

'''
Django 高级视图
'''

from django.shortcuts import render
from .models import Article
# import json
from django.views.decorators.http import require_http_methods, require_GET, require_POST, require_safe
from django.http import HttpResponse

#require_GET = require_http_methods(['GET'])

#require_safe = require_http_methods(['GET','HEAD'])

@require_GET
def index(request):
    # 首页返回所有的文章
    # 只能使用git请求来访问这个视图函数
    # if request.GET.get():
    articles = Article.objects.all()
    return render(request,'index.html',context={"articles":articles})

@require_http_methods(['POST','GET'])
def add_article(request):
    # 如果使用get请求，来访问这个驶入函数，那么返回一个添加文章的html页面
    # 如果使用post请求，来访问这个视图函数，那么就获取提交上来的数据，然后保存
    if request.method == 'GET':
        return render(request,"add_article.html")
    elif request.method == 'POST':
        title = request.POST.get("title")
        content = request.POST.get("content")
        Article.objects.create(title=title,content=content)
        return HttpResponse('success')